'use client'
import 'katex/dist/katex.min.css';

import { Button, Form, Input, List, Modal, Space, Typography } from 'antd';
import React, { useState } from 'react';
import { BlockMath } from 'react-katex';

import { MathPublic } from '@/pao/paoMath';
import { css } from '@emotion/css';

const Class_Client = css`width: 100%; height: 100%;`;

/** 页面属性 */
export type IPageProps = {
}

const Page : React.FC<IPageProps> = (props) => {
  const {className, ...attrs} = props as any;
  const [variables, setVariables] = useState("x,y");
  const [equations, setEquations] = useState<string[]>(['x+2*y', 'x**2+y**2-25']);
  const [result, setResult] = useState("");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentEquation, setCurrentEquation] = useState("");
  const [editIndex, setEditIndex] = useState(-1);
  const [form] = Form.useForm();

  async function calculate() {
    const vars = variables.split(',').map(v => v.trim()).filter(v => v);
		try {
			const result = await MathPublic.solveEquation(equations, vars);
			setResult(`\$\$解方程组：\\begin{cases}${result.equations.map((eq:string)=>eq+' = 0').join('\\\\')}\\end{cases}\$\$\n\$\${结果：${result.result}}\$\$`);
		} catch (error: any) {
			console.error(error);
			setResult(`\$\$计算失败：${error.message}\$\$`);
		}
  }

  const handleAddEquation = () => {
    form.resetFields();
    setCurrentEquation("");
    setEditIndex(-1);
    setIsModalOpen(true);
  };

  const handleEditEquation = (index: number) => {
    form.setFieldsValue({ equation: equations[index] });
    setEditIndex(index);
    setIsModalOpen(true);
  };

  const handleDeleteEquation = (index: number) => {
    setEquations(equations.filter((_, i) => i !== index));
  };

  const handleOk = () => {
    form.validateFields().then(values => {
      if (editIndex >= 0) {
        const newEquations = [...equations];
        newEquations[editIndex] = values.equation;
        setEquations(newEquations);
      } else {
        setEquations([...equations, values.equation]);
      }
      setIsModalOpen(false);
    });
  };

  return (
    <div className={`${Class_Client} ${css`
      background-color: #f2f2f2; 
      border: 1px solid #ccc; 
      overflow: auto; 
      padding: 20px;
      display: flex;
      flex-direction: column;
      gap: 20px;
    `} ${className||''}`} {...attrs}>
      
      <Space direction="vertical" style={{width: '100%'}}>
        <h3>自变量</h3>
        <Input 
          value={variables} 
          onChange={(e) => setVariables(e.target.value)}
          placeholder="输入自变量，用逗号分隔，如: x,y,z"
        />
      </Space>

      <Space direction="vertical" style={{width: '100%'}}>
        <h3>方程组</h3>
        <Button type="primary" onClick={handleAddEquation}>添加方程</Button>
        <List
          bordered
          dataSource={equations}
          renderItem={(item, index) => (
            <List.Item
              actions={[
                <a key="edit" onClick={() => handleEditEquation(index)}>编辑</a>,
                <a key="delete" onClick={() => handleDeleteEquation(index)}>删除</a>
              ]}
            >
              {item}
            </List.Item>
          )}
        />
      </Space>

      <Space direction="vertical" style={{width: '100%'}}>
        <Button type="primary" onClick={calculate}>计算</Button>
        <div style={{
          background: '#fff',
          padding: '16px',
          border: '1px solid #d9d9d9',
          borderRadius: '2px'
        }}>
          {result.split('\n').map((line, i) => (
            line.startsWith('$$') && line.endsWith('$$') ? (
              <BlockMath key={i} math={line.substring(2, line.length-2)} />
            ) : (
              <Typography.Paragraph key={i}>{line}</Typography.Paragraph>
            )
          ))}
        </div>
      </Space>

      <Modal
        title={editIndex >= 0 ? "编辑方程" : "添加方程"}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={() => setIsModalOpen(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="equation"
            label="方程"
            rules={[{ required: true, message: '请输入方程' }]}
          >
            <Input placeholder="例如: x + y = 10" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default Page;